﻿#region

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using PicSizer.Program.FileIO;

#endregion

namespace PicSizer.Program.Logic.Compress
{
    public class Png : CompressItem
    {
        public Png(string imgPath, string outputFilename)
        {
            this.Init(imgPath, outputFilename);
        }

        protected override void WriteToStreamWithQuality(Stream stream, int quality)
        {
            FreeImageAPI.FreeImageBitmap freeImage = null;
            try
            {
                int paletteSize = (int)Algorithm.Range.MapRange(
                    quality,
                    0, 100,
                    10, 256,
                    bias: 0.6);
                freeImage = new FreeImageAPI.FreeImageBitmap(this.Img);
                freeImage.Quantize(FreeImageAPI.FREE_IMAGE_QUANTIZE.FIQ_WUQUANT, paletteSize);
                freeImage.Save(
                    stream,
                    FreeImageAPI.FREE_IMAGE_FORMAT.FIF_PNG,
                    FreeImageAPI.FREE_IMAGE_SAVE_FLAGS.PNG_Z_BEST_SPEED);
            }
            finally
            {
                freeImage?.Dispose();
            }
        }
    }
}